# @Time    : 2019/8/22 14:23
# @Author  : patrick
# @File    : premiumService.py
# @Software: PyCharm
import datetime
import json
import time

import readConfig
from common.assembleJson import AssembleJson
from common.common import readPremiumTable, writePremiumReuslt
from common.configHttp import ConfigHttp
from common.mysqlHelper import MysqlHelper
localReadConfig = readConfig.ReadConfig()
request = ConfigHttp()
aJson = AssembleJson()
sqlHelper = MysqlHelper()


def getHttpResult(**kwargs):
    """
    测试费率接口请求，实际结果
    :return: 总保费
    """
    premiumList = []
    ageRange = kwargs.get("age").split("-")
    # print(ageRange)
    ageUp = int(ageRange[0])
    ageDown = int(ageRange[1])
    for i in range(ageUp, ageDown+1):
        try:
            jsonList = []
            personJson = aJson.person_json(
                salesProductCode=kwargs.get("salesProductCode"),
                coverage=kwargs.get("coverage"),
                paymentPeriod=kwargs.get("paymentPeriod"),
                hasSecurity=kwargs.get("hasSecurity"),
                sex=kwargs.get("sex"),
                age=str(i),
                paymentMethod=kwargs.get("paymentMethod"),
                occupationCode=kwargs.get("occupationCode")
            )
            jsonList.append(personJson)
            header = {"Content-Type": localReadConfig.get_headers("content_type")}
            request.set_headers(header)
            request.set_url(localReadConfig.get_api("person_premium_url"))
            # print(json.dumps(jsonList))
            params = {"searchPerson": json.dumps(jsonList)}
            request.set_params(params)
            result = request.post()
            # print(result.text)
            if result.json()['data'] is not None:
                # print("响应数据：%s" % result.json()['data'])
                totalPremium = result.json()['data']["totalPremium"]
                print("总保费：%s" % totalPremium)
                premiumList.append(totalPremium)
            else:
                print(result.json())
                premiumList.append(result.json())
        except Exception as e:
            print(e)
            continue
        finally:
            time.sleep(3)
    return premiumList


def getDBResult(**kwargs):
    """
    获取数据库费率值，预期结果
    :param kwargs:
    :return:
    """
    totalList = []
    ageList = []
    premiumList = []
    codes = kwargs.get("salesProductCode").split(",")
    paymentPeriod = kwargs.get("paymentPeriod")
    sex = kwargs.get("sex")
    occupationCode = kwargs.get("occupationCode")
    coverage = kwargs.get("coverage").split(",")
    ageRange = kwargs.get("age").split("-")
    ageUp = int(ageRange[0])
    ageDown = int(ageRange[1])
    for i in range(ageUp, ageDown + 1):
        # print(codes.__len__())
        ageList.append(i)
        premium = 0.00
        for j in range(codes.__len__()):
            # 判断productCode进入不同费率ID拼接分支
            if codes[j] == "LW03" or codes[j] == "LW05" or codes[j] == "MI01" or codes[j] == "MI03" or \
                    codes[j] == "MI04" or codes[j] == "LWA1":
                # 计算基本保费和职业加费
                # 拼接基本费率ID，表t_basic_premium_rate
                productID = ["%s|A1|%s|%s" % (codes[j], sex, i)]
                # 拼接职业费率ID，表t_job_premium_rate
                jobID = ["%s|A2|%s" % (codes[j], occupationCode)]
                # print(productID)
                # print(jobID)
                premium += sqlHelper.queryBasicPremium(productID, coverage[j]) + sqlHelper.queryJobAdd(jobID, coverage[j])
            elif codes[j] == "LW04" or codes[j] == "LW06" or codes[j] == "MI02" or codes[j] == "LWA2" or \
                    codes[j] == "LTA1" or codes[j] == "LTA2" or codes[j] == "LTA3" or codes[j] == "LTA4" or\
                    codes[j] == "MIP1":
                productID = ["%s|A1|%s|%s|%s" % (codes[j], paymentPeriod, sex, i)]
                jobID = ["%s|A2|%s" % (codes[j], occupationCode)]
                # print(productID)
                premium += sqlHelper.queryBasicPremium(productID, coverage[j]) + sqlHelper.queryJobAdd(jobID, coverage[j])
            elif codes[j] == "AS01" or codes[j] == "AS02" or codes[j] == "AS03":
                productID = ["%s|A1|%s|%s|%s" % (codes[j], i, sex, paymentPeriod)]
                jobID = ["%s|A2|%s" % (codes[j], occupationCode)]
                # print(productID)
                premium += sqlHelper.queryBasicPremium(productID, coverage[j]) + sqlHelper.queryJobAdd(jobID, coverage[j])
            elif codes[j] == "LE01" or codes[j] == "LE02" or codes[j] == "MMA6" or codes[j] == "MMA7":
                productID = ["%s|A1|%s|%s" % (codes[j], i, sex)]
                jobID = ["%s|A2|%s" % (codes[j], occupationCode)]
                # print(productID)
                premium += sqlHelper.queryBasicPremium(productID, coverage[j]) + sqlHelper.queryJobAdd(jobID, coverage[j])
            elif codes[j] == "AA02" or codes[j] == "AAA2" or codes[j] == "MMA3" or codes[j] == "MMA4" or \
                    codes[j] == "MMA5":
                productID = ["%s|A1" % (codes[j])]
                jobID = ["%s|A2|%s" % (codes[j], occupationCode)]
                # print(productID)
                premium += sqlHelper.queryBasicPremium(productID, coverage[j]) + sqlHelper.queryJobAdd(jobID, coverage[j])
        premiumList.append(premium)
    totalList.append(premiumList), totalList.append(ageList)
    # print(premiumList)
    return totalList


if __name__ == '__main__':
    result = readPremiumTable("Premium_Test_Data.xlsx")
    actual_premium = list()
    expect_premium = list()
    # 定义结果文件名
    now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    filename = "Premium_Test_Result_%s.xls" % now
    for i in range(0, result.__len__()):
        actual_premium = getHttpResult(salesProductCode=result[i][0], coverage=str(result[i][1]), sex=result[i][2], age=result[i][3],
                  hasSecurity=result[i][4], paymentPeriod=result[i][5], paymentMethod=result[i][6], occupationCode=result[i][7])
        print(actual_premium)
        expect_premium = getDBResult(salesProductCode=result[i][0], coverage=str(result[i][1]), sex=result[i][2], age=result[i][3],
                  hasSecurity=result[i][4], paymentPeriod=result[i][5], occupationCode=result[i][7])
        print(expect_premium)

        writePremiumReuslt(
            filename=filename,
            excepctList=expect_premium,
            actualList=actual_premium,
            salesProductCode=result[i][0],
            coverage=str(result[i][1]),
            sex=result[i][2],
            age=result[i][3],
            hasSecurity=result[i][4],
            paymentPeriod=result[i][5],
            paymentMethod=result[i][6],
            occupationCode=result[i][7]
        )
        print("-----------------------------------------")




